
#include "EventSystem.h"


//Constructor
EventSystem* EventSystem::GetInstance(void)
{
	static EventSystem instance;
	return &instance;
}


//Register
void EventSystem::Register(string eventType, EventListener* listener)
{
	listeners.insert(make_pair(eventType, listener));
}


//Unregister
void EventSystem::Unregister(string eventType, EventListener *listener)
{
	pair<multimap<string, EventListener*>::iterator,multimap<string, EventListener*>::iterator> range;
	range = listeners.equal_range(eventType);
	for(multimap<string, EventListener*>::iterator mmIter = range.first; mmIter != range.second; mmIter++)
	{
		if((*mmIter).second == listener)
		{
			mmIter = listeners.erase(mmIter);
			break;
		}
	}
}


//Update
void EventSystem::Update(void)
{
	while(events.size())
	{
		Event* e = &events.front();
		pair<multimap<string, EventListener*>::iterator,multimap<string, EventListener*>::iterator> range;
		range = listeners.equal_range(e->GetEventType());
		for(multimap<string, EventListener*>::iterator mmIter = range.first; mmIter != range.second; mmIter++)
			(*mmIter).second->HandleEvent(e);
		events.pop_front();
	}
}


//Send event
void EventSystem::SendEvent(string eventType, void* data, void* target, void* source)
{
	Event newEvent(eventType, data, target, source);
	events.push_back(newEvent);
}


//Shutdown
void EventSystem::Shutdown(void)
{
	events.clear();
	listeners.clear();
}
